import 'package:flutter/material.dart';
import 'package:peach/config/_.dart';
import 'package:peach/utils/_.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

/// 异步数据请求，封装成组件，数据类型通过泛型传入
class FutureBuilderWidget<O> extends StatelessWidget {
  final Function future; // future 异步方法
  final Widget Function(O res) success; // 请求成功后展示的widget方法
  FutureBuilderWidget({
    @required this.future,
    @required this.success
  });

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: future(),
      builder: (BuildContext context, AsyncSnapshot<O> snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return Center(
              child: SpinKitWave(color: ColorConfig.ThemeColor, itemCount: 3, size: 40),
            );
            break;
          case ConnectionState.done:
            if (snapshot.hasError) {
              return Container(
                margin: EdgeInsets.only(top: Screen.setHeight(100)),
                alignment: AlignmentDirectional.center,
                padding: EdgeInsets.all(10),
                child: Column(
                  children: [
                    Icon(Icons.error,size: 50,color: ColorConfig.ThemeColor,),
                    SizedBox(height: 10,),
                    Text("网络出现问题", style: TextStyle(fontSize: 16,color: ColorConfig.TitleColor),),
                    SizedBox(height: 8,),
                    Text(snapshot.error.toString(),style: TextStyle(fontSize: 14,color: ColorConfig.TextColor),),
                    InkWell(
                      onTap: () {
                        FutureBuilderWidget(future: future, success: success,);
                      },
                      child: Icon(Icons.refresh,size: 30,color: ColorConfig.ThemeColor,),
                    ),
                  ],
                ),
              );
            } else {
              return success(snapshot.data);
            }
            break;
          default:
            return null;
        }
      },
    );
  }
}

